package com.huaxin.hxcloud.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.SVGViewDTO;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.work.HxSvgShowAdapter;
import com.huaxin.hxcloud.work.HxSvgShowFragment;
import com.huaxindata.im.main.share.ShareActivity;
import com.huaxindata.im.model.entity.ChatMessageBody;
import com.huaxindata.im.model.entity.ChatSvgMessageBody;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 显示SVG图
 */
public class SVGShowActivity extends BaseActivity implements AdapterView.OnItemClickListener {


    @BindView(R.id.more)
    ImageView more;
    @BindView(R.id.toolbar)
    Toolbar   toolbar;
    @BindView(R.id.tv_unread)
    TextView  mTvUnread;
    @BindView(R.id.listview)
    ListView  mListview;
    @BindView(R.id.view_diliver)
    View      diliver;

    private String mStatioCode;
    private String mDeviceCode;

    private List<SVGViewDTO.SvgListBean> mSvgBean;
    private HxSvgShowAdapter             mSvgAdapter;
    HxSvgShowFragment myFragment;
    private FragmentTransaction  mFragmentTransaction;
    private File[]               mFiles;
    private Map<String, Boolean> mSvgState;

    @Override
    protected int getContentViewId() {
        return R.layout.svglist;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initData() {
        mFiles = new File(getExternalCacheDir().getPath()).listFiles();
        mSvgState = new HashMap<>();
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        toolbar.setTitle("工艺图");
        more.setImageResource(R.drawable.icon_share);
        more.setVisibility(View.VISIBLE);
        mSvgBean = new ArrayList<>();
        mSvgAdapter = new HxSvgShowAdapter(this, mSvgBean);
        mListview.setAdapter(mSvgAdapter);

        //创建MyFragment对象
        myFragment = HxSvgShowFragment.newInstance();
        mFragmentTransaction = getSupportFragmentManager().beginTransaction();
        mFragmentTransaction.replace(R.id.fragment_container, myFragment);


        //通过bundle传值给MyFragment
        Bundle bundle = new Bundle();
        bundle.putString(HxSvgShowFragment.TAG, mStatioCode);
        myFragment.setArguments(bundle);

        mFragmentTransaction.commit();
        mListview.setOnItemClickListener(this);
    }

    @Override
    public void requestData() {
        ApiRequestData(LOADING);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (!extras.containsKey(Constants.IK_DEVICE_CODE)) {
            finish();
        }
        mDeviceCode = extras.getString(Constants.IK_DEVICE_CODE);
        mStatioCode = extras.getString(Constants.IK_STATION_CODE);
    }

    /**
     * 请求数据
     *
     * @param status
     */
    private void ApiRequestData(int status) {
        updateLoadStatus(status);
        Call<SVGViewDTO> call = HxTransmitRequestHelper.getRequestApi().getSVGView(mDeviceCode,mStatioCode);
        autoClose(call);
        Log.d(TAG, "ApiRequestData:---> " + call.request().url());
        call.enqueue(new Callback<SVGViewDTO>() {
            @Override
            public void onResponse(Call<SVGViewDTO> call, Response<SVGViewDTO> response) {
                SVGViewDTO svgView = response.body();
                if (svgView != null && svgView.isSuccessful()) {
                    if (svgView.getSvgList() == null || svgView.getSvgList().size() == 0) {
                        updateLoadStatus(LOAD_NO_DATA);
                        Toast.makeText(SVGShowActivity.this,svgView.getMsg(),Toast.LENGTH_LONG).show();
                        more.setVisibility(View.GONE);
                        return;
                    } else if (svgView.getSvgList().size() == 1) {
                        //隐藏listview
                        mListview.setVisibility(View.GONE);
                        diliver.setVisibility(View.GONE);

                    } else {
                        Log.d(TAG, "onResponse: " + svgView.toString());
                        mListview.setVisibility(View.VISIBLE);
                        diliver.setVisibility(View.VISIBLE);
                    }
                    mSvgBean.addAll(svgView.getSvgList());
                    //初始化第一条数据
                    setSvgExist(svgView.getSvgList().get(0));
                    more.setVisibility(View.VISIBLE);
                    updateLoadStatus(LOAD_SUCCESS);

                } else {
                    updateLoadStatus(LOAD_ERROR);
                    more.setVisibility(View.GONE);
                }
            }

            @Override
            public void onFailure(Call<SVGViewDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
                more.setVisibility(View.GONE);
            }
        });
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        //拿到当前位置
        // mPosition = position;
        mSvgAdapter.setPosition(position);
        //即使刷新adapter
        mSvgAdapter.notifyDataSetChanged();
        setSvgExist(mSvgBean.get(position));
    }


    @OnClick({R.id.more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.more:
                if (mSvgBean != null && mSvgBean.size() > 0) {
                    //站点 code 用于查看svg图  stationcode|devicecode 的拼接
                    Log.e("lwjing","mDeviceCode="+mDeviceCode+"  mStatioCode="+mStatioCode);
                   // final String code = mDeviceCode;
                    final String code = mStatioCode+"|"+mDeviceCode;
                    final String name = mSvgBean.get(0).getViewName();
                    final String size = mSvgBean.get(0).getFileSize();
                    final String url = mSvgBean.get(0).getImgUrl();
                    final ChatSvgMessageBody message = new ChatSvgMessageBody(ChatMessageBody.Type.SVG,code, url, name, size);
                    Intent intent = new Intent(this, ShareActivity.class);
                    intent.putExtra("message_type",ChatMessageBody.Type.SVG);
                    intent.putExtra("message", message);
                    startActivity(intent);
                }
                break;
        }
    }

    /**
     * 设置svg是否存在
     *
     * @param svgListBean
     */
    public void setSvgExist(SVGViewDTO.SvgListBean svgListBean) {
        File[] files = new File(getExternalCacheDir().getPath()).listFiles();
        Log.d(TAG, "setData: " + files.length);
        for (int i = 0; i < files.length; i++) { //是否缓存中存在
            if ((svgListBean.getFileCode() + ".html").equals(files[i].getName())) {
                svgListBean.setExist(true);
            }
        }
        myFragment.setData(svgListBean);
    }


}
